package com.sjgtw.cloud.web.keysArea.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.sjgtw.cloud.common.core.constant.CacheConstants;
import com.sjgtw.cloud.common.core.utils.DateUtils;
import com.sjgtw.cloud.common.core.utils.SecurityUtils;
import com.sjgtw.cloud.common.core.utils.StringUtils;
import com.sjgtw.cloud.common.core.web.domain.AjaxResult;
import com.sjgtw.cloud.common.redis.service.RedisService;
import com.sjgtw.cloud.service.SystemServerService;
import com.sjgtw.cloud.system.api.model.LoginUser;
import com.sjgtw.cloud.web.keysArea.domain.KeysAreas;
import com.sjgtw.cloud.web.keysArea.mapper.KeysAreasMapper;
import com.sjgtw.cloud.web.keysArea.service.IKeysAreasService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

/**
 * 防洪重点地段管理Service业务层处理
 * 
 * @author ruoyi
 * @date 2024-03-15
 */
@Service
public class KeysAreasServiceImpl implements IKeysAreasService
{
    @Autowired
    private KeysAreasMapper keysAreasMapper;

    @Autowired
    private RedisService redisService;

    @Autowired
    private SystemServerService systemServerService;

    /**
     * 查询防洪重点地段管理
     * 
     * @param id 防洪重点地段管理主键
     * @return 防洪重点地段管理
     */
    @Override
    public KeysAreas selectKeysAreasById(Long id)
    {
        return keysAreasMapper.selectKeysAreasById(id);
    }

    /**
     * 查询防洪重点地段管理列表
     * 
     * @param keysAreas 防洪重点地段管理
     * @return 防洪重点地段管理
     */
    @Override
    public List<Map<String,Object>> selectKeysAreasList(KeysAreas keysAreas)
    {
        List<Map<String,Object>> list = keysAreasMapper.selectKeysAreasList(keysAreas);
        Set<String> userIds = new HashSet();
        for (int i=0; i<list.size(); i++) {
            Map<String, Object> map = list.get(i);
            Object headId = map.get("headId");
            Object cadreId = map.get("cadreId");
            if (headId != null) {
                String[] headIds = headId.toString().split(",");
                List<String> strings = Arrays.asList(headIds);
                for (int k = 0; k < strings.size(); k++) {
                    if(StringUtils.isNotEmpty(strings.get(k))){
                        userIds.add(strings.get(k));
                    }
                }
            }
            if (cadreId != null) {
                String[] cadreIds = cadreId.toString().split(",");
                List<String> strings = Arrays.asList(cadreIds);
                for (int k = 0; k < strings.size(); k++) {
                    if(StringUtils.isNotEmpty(strings.get(k))){
                        userIds.add(strings.get(k));
                    }
                }
            }
        }
        if (userIds.size() > 0) {
            String userIds_ = userIds.stream().collect(Collectors.joining(","));
            AjaxResult userResult = systemServerService.getUserByIds(userIds_);
            Map<String, String> userMap = new HashMap<>();
            if (userResult != null) {
                Object object = userResult.get("data");
                if (object != null) {
                    JSONArray jsonArray = JSONArray.parseArray(JSONArray.toJSONString(object));
                    if (!jsonArray.isEmpty()) {
                        for (int i=0; i<jsonArray.size();i++) {
                            JSONObject json = jsonArray.getJSONObject(i);
                            userMap.put(json.getString("userId"), json.getString("userName"));
                        }
                    }
                }
            }
            for (int i=0; i<list.size(); i++) {
                Map<String, Object> map = list.get(i);
                map.put("cadre","");
                map.put("head","");
                Object headId = map.get("headId");
                Object cadreId = map.get("cadreId");
                if (headId != null && !"".equals(headId)) {
                    String[] headIds = headId.toString().split(",");
                    String[] head = new String[headIds.length];
                    for (int j=0;j<headIds.length;j++) {
                        head[j] = userMap.get(headIds[j]);
                    }
                    map.put("head", String.join(",", head));
                }
                if (cadreId != null && !"".equals(cadreId)) {
                    String[] cadreIds = cadreId.toString().split(",");
                    String[] cadre = new String[cadreIds.length];
                    for (int j=0;j<cadreIds.length;j++) {
                        cadre[j] = userMap.get(cadreIds[j]);
                    }
                    map.put("cadre", String.join(",", cadre));
                }
            }
        }
        return list;
    }

    /**
     * 新增防洪重点地段管理
     * 
     * @param keysAreas 防洪重点地段管理
     * @return 结果
     */
    @Override
    public int insertKeysAreas(KeysAreas keysAreas)
    {
        String token = SecurityUtils.getToken();
        String userKey = CacheConstants.LOGIN_TOKEN_KEY + token;
        LoginUser user = redisService.getCacheObject(userKey);

        if (user != null)
            keysAreas.setCreateBy(user.getUsername());
        keysAreas.setCreateTime(DateUtils.getNowDate());
        return keysAreasMapper.insertKeysAreas(keysAreas);
    }

    /**
     * 修改防洪重点地段管理
     * 
     * @param keysAreas 防洪重点地段管理
     * @return 结果
     */
    @Override
    public int updateKeysAreas(KeysAreas keysAreas)
    {
        String token = SecurityUtils.getToken();
        String userKey = CacheConstants.LOGIN_TOKEN_KEY + token;
        LoginUser user = redisService.getCacheObject(userKey);

        keysAreas.setUpdateBy(user.getUsername());
        keysAreas.setUpdateTime(DateUtils.getNowDate());
        return keysAreasMapper.updateKeysAreas(keysAreas);
    }

    /**
     * 批量删除防洪重点地段管理
     * 
     * @param ids 需要删除的防洪重点地段管理主键
     * @return 结果
     */
    @Override
    public int deleteKeysAreasByIds(Long[] ids)
    {
        return keysAreasMapper.deleteKeysAreasByIds(ids);
    }

    /**
     * 删除防洪重点地段管理信息
     * 
     * @param id 防洪重点地段管理主键
     * @return 结果
     */
    @Override
    public int deleteKeysAreasById(Long id)
    {
        return keysAreasMapper.deleteKeysAreasById(id);
    }

    @Override
    public List<KeysAreas> selectKeysAreasList2(KeysAreas keysAreas) {
        List<KeysAreas> list = keysAreasMapper.selectKeysAreasList2(keysAreas);
        Set<String> userIds = new HashSet();
        for (int i=0; i<list.size(); i++) {
            KeysAreas eneity = list.get(i);
            String headId = eneity.getHeadId();
            String cadreId = eneity.getCadreId();
            if (headId != null) {
                String[] headIds = headId.split(",");
                List<String> strings = Arrays.asList(headIds);
                for (int k = 0; k < strings.size(); k++) {
                    if(StringUtils.isNotEmpty(strings.get(k))){
                        userIds.add(strings.get(k));
                    }
                }
            }
            if (cadreId != null) {
                String[] cadreIds = cadreId.split(",");
                List<String> strings = Arrays.asList(cadreIds);
                for (int k = 0; k < strings.size(); k++) {
                    if(StringUtils.isNotEmpty(strings.get(k))){
                        userIds.add(strings.get(k));
                    }
                }
            }
        }
        if (userIds.size() > 0) {
            String userIds_ = userIds.stream().collect(Collectors.joining(","));
            AjaxResult userResult = systemServerService.getUserByIds(userIds_);
            Map<String, String> userMap = new HashMap<>();
            if (userResult != null) {
                Object object = userResult.get("data");
                if (object != null) {
                    JSONArray jsonArray = JSONArray.parseArray(JSONArray.toJSONString(object));
                    if (!jsonArray.isEmpty()) {
                        for (int i=0; i<jsonArray.size();i++) {
                            JSONObject json = jsonArray.getJSONObject(i);
                            userMap.put(json.getString("userId"), json.getString("userName"));
                        }
                    }
                }
            }
            for (int i=0; i<list.size(); i++) {
                KeysAreas eneity = list.get(i);
                String headId = eneity.getHeadId();
                String cadreId = eneity.getCadreId();
                if (headId != null) {
                    String[] headIds = headId.split(",");
                    String[] head = new String[headIds.length];
                    for (int j=0;j<headIds.length;j++) {
                        head[j] = userMap.get(headIds[j]);
                    }
                    eneity.setHead(String.join(",", head));
                }
                if (cadreId != null) {
                    String[] cadreIds = cadreId.split(",");
                    String[] cadre = new String[cadreIds.length];
                    for (int j=0;j<cadreIds.length;j++) {
                        cadre[j] = userMap.get(cadreIds[j]);
                    }
                    eneity.setCadre(String.join(",", cadre));
                }
            }
        }
        return list;
    }

    @Override
    public List<String> check(List<KeysAreas> entities) {
        List<String> errors = new ArrayList<>();
        String token = SecurityUtils.getToken();
        String userKey = CacheConstants.LOGIN_TOKEN_KEY + token;
        LoginUser user = redisService.getCacheObject(userKey);

        List<String> userNames = extractAndDeduplicateUserNames(entities);

        AjaxResult userResult = systemServerService.getUserByNames(StringUtils.join(userNames, ","));
        Map<String, Long> userMap = new HashMap<>();
        if (userResult != null) {
            Object object = userResult.get("data");
            if (object != null) {
                JSONArray jsonArray = JSONArray.parseArray(JSONArray.toJSONString(object));
                if (!jsonArray.isEmpty()) {
                    for (int i=0; i<jsonArray.size();i++) {
                        JSONObject json = jsonArray.getJSONObject(i);
                        userMap.put(json.getString("userName"), json.getLong("userId"));
                    }
                }
            }
        }

        List<String> deptNames = extractAndDeduplicateNames(entities);
        AjaxResult result = systemServerService.getDeptByNames(StringUtils.join(deptNames, ","));
        Map<String, Long> deptMap = new HashMap<>();
        if (result != null) {
            Object object = result.get("data");
            if (object != null) {
                JSONArray jsonArray = JSONArray.parseArray(JSONArray.toJSONString(object));
                if (!jsonArray.isEmpty()) {
                    for (int i=0; i<jsonArray.size();i++) {
                        JSONObject json = jsonArray.getJSONObject(i);
                        deptMap.put(json.getString("deptName"), json.getLong("deptId"));
                    }
                }
            }
        }

        for (KeysAreas entity : entities) {
            if (StringUtils.isNotEmpty(entity.getWorkArea())) {
                if (deptMap.containsKey(entity.getWorkArea())) {
                    entity.setWorkAreaId(deptMap.get(entity.getWorkArea()));
                } else {
                    errors.add("序号为" + entity.getNum() + "行数据所属工区不存在");
                }
            }

            if (StringUtils.isNotEmpty(entity.getHead())) {
                List<String> headList = Arrays.asList(entity.getHead().split(","));
                String headId = "";
                for (String head : headList) {
                    if (userMap.containsKey(head)) {
                        headId += userMap.get(head) + ",";
                    } else {
                        errors.add("序号为" + entity.getNum() + "行数据责任人" + head + "不存在");
                    }
                }
                if (headId.length() > 0) {
                    headId = headId.substring(0, headId.length() - 1);
                }
                entity.setHeadId(headId);
            }

            if (StringUtils.isNotEmpty(entity.getCadre())) {
                List<String> cadreList = Arrays.asList(entity.getCadre().split(","));
                String cadreId = "";
                for (String cadre : cadreList) {
                    if (userMap.containsKey(cadre)) {
                        cadreId += userMap.get(cadre) + ",";
                    } else {
                        errors.add("序号为" + entity.getNum() + "行数据包保干部" + cadre + "不存在");
                    }
                }
                if (cadreId.length() > 0) {
                    cadreId = cadreId.substring(0, cadreId.length() - 1);
                }
                entity.setCadreId(cadreId);
            }

            if (user != null) {
                entity.setCreateBy(user.getUsername());
            }
            entity.setCreateTime(DateUtils.getNowDate());
        }
        return errors;
    }

    @Override
    public void batchSave(List<KeysAreas> entities) {
        if (entities != null && entities.size() > 0) {
            if (entities.size() >= 200) {
                int index = 0;
                while (index <= entities.size()) {
                    int last = Math.min(index + 200, entities.size());
                    List<KeysAreas> temp = entities.subList(index, last );
                    if (temp != null && temp.size() > 0) {
                        keysAreasMapper.batchSave(temp);
                    }
                    index += 200;
                }
            } else {
                keysAreasMapper.batchSave(entities);
            }
        }
    }

    private static List<String> extractAndDeduplicateNames(List<KeysAreas> entities) {
        Set<String> uniqueNamesSet = new HashSet<>();

        for (KeysAreas entity : entities) {
            uniqueNamesSet.add(entity.getWorkArea());
        }

        return new ArrayList<>(uniqueNamesSet);
    }

    private static List<String> extractAndDeduplicateUserNames(List<KeysAreas> entities) {
        Set<String> uniqueNamesSet = new HashSet<>();

        for (KeysAreas entity : entities) {
            if(entity.getHead() != null){
                uniqueNamesSet.addAll(Arrays.asList(entity.getHead().split(",")));
            }
            if(entity.getCadre() != null){
                uniqueNamesSet.addAll(Arrays.asList(entity.getCadre().split(",")));
            }


        }

        return new ArrayList<>(uniqueNamesSet);
    }
}
